﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class UIManager : MonoBehaviour
{
    LinkedList<BaseWidget> mShowWidgetLists = new LinkedList<BaseWidget>();

    static UIManager mInst;
    public static UIManager Inst { get { return mInst; } }
    void Awake()
    {
        mInst = this;
    }
    void Start()
    {
        GameObject.DontDestroyOnLoad(gameObject);
    }

    public BaseWidget Show(string name)
    {
        if (!UIDatas.Datas.ContainsKey(name))
        {
            Debug.LogError("不存在" + name);
            return null;
        }
        var Data = UIDatas.Datas[name];
        GameObject newUI = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>(Data.PrefabPath));
        newUI.transform.SetParent(transform, false);
        BaseWidget newWidget = newUI.GetComponent<BaseWidget>();
        newWidget.Name = name;
        newWidget.OnLoad();
        mShowWidgetLists.AddLast(newWidget);
        return newWidget;
    }
    public void Close(string name)
    {
        var bw = Get(name);
        mShowWidgetLists.Remove(bw);
        GameObject.Destroy(bw.gameObject);
    }
    public void Close(BaseWidget bw)
    {
        mShowWidgetLists.Remove(bw);
        GameObject.Destroy(bw.gameObject);
    }

    public BaseWidget Get(string name)
    {
        foreach (BaseWidget bw in mShowWidgetLists)
        {
            if (bw.Name == name)
            {
                return bw;
            }
        }
        return null;
    }
}

public class BaseWidget : MonoBehaviour
{
    public string Name;
    public virtual void OnLoad() { }
    public virtual void OnExit() { }
}